package com.atgouwu.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atgouwu.mall.common.es.SkuEsModel;
import com.atgouwu.mall.product.dao.ProductDao;
import com.atgouwu.mall.product.entity.CategoryEntity;
import com.atgouwu.mall.product.service.ProductService;
import com.atgouwu.mall.product.vo.SearchParam;
import com.atgouwu.mall.product.vo.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("productService")
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    //根据条件搜索商品(从数据库)
    @Override
    public SearchResult searchDb(SearchParam param) {
        SearchResult result = new SearchResult();
        if (!StringUtils.isEmpty(param.getCategoryName())) {
            List<SearchResult.BrandVo> brands = productDao.getBrands(param.getCategoryName()); //获取品牌
            result.setTrademarkList(brands);
            List<SearchResult.CatalogVo> catagoryOnes = productDao.getCatagoryOnes(param.getCategoryName()); //获取分类及子分类
//            if(!CollectionUtils.isEmpty(catagoryOnes)){
//                List<SearchResult.CatalogVo> catagoryTwos = productDao.getCatagoryTwos(catagoryOnes);
//                if(!CollectionUtils.isEmpty(catagoryOnes)){
//                    List<SearchResult.CatalogVo> catagoryThrees = productDao.getCatagoryThrees(catagoryTwos);
//                }
//            }
            result.setCatalogs(catagoryOnes);
            List<Map<String, Object>> attrs = productDao.getAttrs(param.getCategoryName()); //获取属性
//            List<SearchResult.AttrVo> attrVos = attrs.stream().map((attrMap) -> {
//                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
//                attrVo.setAttrId(Long.valueOf(attrMap.get("attrId").toString()));
//                attrVo.setAttrName(attrMap.get("attrName").toString());
//                attrVo.setAttrValue(Arrays.asList(attrMap.get("attrValues").toString().split(";")));
//                return attrVo;
//            }).collect(Collectors.toList());
            List<SearchResult.AttrVo>  attrVoss = JSON.parseArray(JSON.toJSONString(attrs), SearchResult.AttrVo.class);
            attrVoss = attrVoss.stream().filter(f -> !StringUtils.isEmpty(f.getAttrValues())).peek(p -> p.setAttrValue(Arrays.asList(p.getAttrValues().split(";")))).collect(Collectors.toList());
            result.setAttrsList(attrVoss);
            List<SkuEsModel> skuEsModels = productDao.getSkuEsModels(param.getCategoryName()); //获取商品信息
            result.setGoodsList(skuEsModels);
            result.setPageNum(1);
            result.setTotal(100L);
            result.setTotalPages(10);
        }
        return result;
    }
}
